import java.io.IOException;
import java.util.Vector;

import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.UUID;

import com.intel.bluetooth.BlueCoveImpl;

public class L2CAPServer {

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) {
		BlueCoveImpl.useThreadLocalBluetoothStack();
		// BlueCoveImpl.setConfigProperty("bluecove.stack", "toshiba");

		/*
		 * try { Vector vec = BlueCoveImpl.getLocalDevicesID(); for (int
		 * i=0; i<vec.size(); i++){ System.out.println(vec.elementAt(i)); }
		 * 
		 * } catch (BluetoothStateException e2) {}
		 */

		/*
		 * try {
		 * System.out.println(BlueCoveImpl.getThreadBluetoothStackID()); }
		 * catch (BluetoothStateException e2) {}
		 */

		BlueCoveImpl.setConfigProperty("bluecove.stack", "mac");

		try {
			final Object id1 = BlueCoveImpl.getThreadBluetoothStackID();
		
		//System.out.println(""+id1);
		
		
		new Thread() {
			public void run() {
				UUID uuid = new UUID("1001", true);
				String url = "btl2cap://localhost:" + uuid
						+ ";ReceiveMTU=128;TransmitMTU=128";
				// on linux
				//BlueCoveImpl.setConfigProperty("bluecove.deviceID", "0");

				try {
					//Object id1 = BlueCoveImpl.getThreadBluetoothStackID();
					BlueCoveImpl.setThreadBluetoothStackID(id1);

					L2CAPServerHandler handler = new L2CAPServerHandler(url);
					handler.run();
					System.out.println("started first thread...");

				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
		}.start();
		
		} catch (BluetoothStateException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}

		// BlueCoveImpl.setConfigProperty("bluecove.stack", "toshiba");

		new Thread() {
			public void run() {
				// on linux
				//BlueCoveImpl.setConfigProperty("bluecove.deviceID", "2");

				BlueCoveImpl.setConfigProperty("bluecove.stack", "winsock");

				Object id2 = null;
				try {
					id2 = BlueCoveImpl.getThreadBluetoothStackID();
					BlueCoveImpl.setThreadBluetoothStackID(id2);
				} catch (BluetoothStateException e1) {
				}

				while (true) {
					try {
						LocalDevice localDevice = LocalDevice
								.getLocalDevice();
						BluetoothDiscovery bluetoothDiscovery = new BluetoothDiscovery(
								localDevice);

						bluetoothDiscovery.startDeviceDiscovery();
						Vector remoteDevices = bluetoothDiscovery
								.getRemoteDevices();

						for (int i = 0; i < remoteDevices.size(); i++) {
							RemoteDevice rDevice = (RemoteDevice) remoteDevices
									.elementAt(i);
							// bluetoothDiscovery.startServiceDiscovery(rDevice,
							// "9106");
						}
					} catch (Exception e) {
					}

				}
			}
		}.start();
		System.out.println("started second thread...");

	}
}
